import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { service } from '@ember/service';

export default class TeamProjectParticipantsListComponent extends Component {
  @service api;
  @service message;
  
  @tracked showModal = false;
  @tracked showBatchModal = false;
  @tracked editingParticipant = null;
  @tracked selectedRequirementId = '';
  @tracked selectedMemberId = '';
  @tracked selectedType = '';
  @tracked queryStartTime = '';
  @tracked queryEndTime = '';
  @tracked memberName = '';
  @tracked isLoading = false;
  @tracked batchFormData = {
    requirementId: '',
    batchStr: ''
  };
  @tracked formData = {
    requirementId: '',
    memberId: '',
    startTime: '',
    endTime: '',
    workload: 0,
    role: '',
    workItem: '',
    type: ''
  };

  constructor() {
    super(...arguments);
    // 初始化时间范围
    this.initializeTimeRange();
  }

  // 获取需求选项（不包含"全部需求"选项，由组件自动处理）
  get requirementOptions() {
    return this.args.requirements?.map(req => ({
      id: req.id?.toString(),
      name: req.name
    })) || [];
  }

  // 获取表单中的需求选项（不包含"全部需求"）
  get requirementOptionsForForm() {
    return this.args.requirements?.map(req => ({
      id: req.id?.toString(),
      name: req.name
    })) || [];
  }

  // 获取人员选项
  get memberOptions() {
    return this.args.members?.map(member => ({
      id: member.id?.toString(),
      name: `${member.name} (${member.type})`
    })) || [];
  }

  // 获取类型选项
  get typeOptions() {
    return [
      { id: '功能开发', name: '功能开发' },
      { id: '技术分析', name: '技术分析' },
      { id: '缺陷修复', name: '缺陷修复' },
      { id: '会议', name: '会议' },
      { id: '技术支持', name: '技术支持' }
    ];
  }

  // 计算工作量（单位：人天）- 保留此方法用于显示，但表单中改为手动输入
  calculateWorkload(startTime, endTime) {
    if (!startTime || !endTime) return 0;
    
    const start = new Date(startTime);
    const end = new Date(endTime);
    const timeDiff = end.getTime() - start.getTime();
    const days = Math.max(1, Math.ceil(timeDiff / (1000 * 60 * 60 * 24)));
    
    return days;
  }

  // 初始化时间范围（当前时间±14天）
  initializeTimeRange() {
    const today = new Date();
    const startDate = new Date(today);
    startDate.setDate(today.getDate() - 14);
    const endDate = new Date(today);
    endDate.setDate(today.getDate() + 14);
    
    this.queryStartTime = startDate.toISOString().split('T')[0];
    this.queryEndTime = endDate.toISOString().split('T')[0];
  }


  // 加载参与人员数据
  async loadParticipants() {
    this.isLoading = true;
    
    try {
      const params = {};
      
      if (this.selectedRequirementId) {
        params.requirementId = this.selectedRequirementId;
      }
      
      if (this.selectedMemberId) {
        params.memberId = this.selectedMemberId;
      }
      
      if (this.selectedType) {
        params.type = this.selectedType;
      }
      
      if (this.queryStartTime) {
        params.queryStartTime = this.queryStartTime;
      }
      
      if (this.queryEndTime) {
        params.queryEndTime = this.queryEndTime;
      }
      
      if (this.memberName.trim()) {
        params.memberName = this.memberName.trim();
      }
      
      // 触发父组件应用筛选条件（客户端筛选，不再请求接口）
      this.args.onRefresh?.(params);
    } catch (error) {
      console.error('加载参与人员数据失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 获取带有详细信息的参与人员列表
  get participantsWithDetails() {
    return (this.args.filteredParticipants || []).map(participant => {
      // 优先使用后端返回的名称信息，如果没有则从传入的props中查找
      const requirementName = participant.requirementName ||
        this.args.requirements?.find(r => r.id.toString() === participant.requirementId?.toString())?.name ||
        '未知需求';
      
      const memberName = participant.memberName ||
        this.args.members?.find(m => m.id.toString() === participant.memberId?.toString())?.name ||
        '未知人员';
      
      return {
        ...participant,
        requirementName,
        memberName,
        workload: participant.workload,
        workItem: participant.workItem,
        type: participant.type || ''
      };
    });
  }

  // 获取筛选后的参与人员列表（前端筛选，用于显示）
  get filteredParticipants() {
    return this.participantsWithDetails;
  }

  @action
  filterByRequirement(requirementId) {
    this.selectedRequirementId = requirementId;
    this.loadParticipants();
  }

  @action
  filterByMember(memberId) {
    this.selectedMemberId = memberId;
    this.loadParticipants();
  }

  @action
  filterByType(type) {
    this.selectedType = type;
    this.loadParticipants();
  }

  @action
  updateQueryStartTime(event) {
    this.queryStartTime = event.target.value;
    this.loadParticipants();
  }

  @action
  updateQueryEndTime(event) {
    this.queryEndTime = event.target.value;
    this.loadParticipants();
  }

  @action
  updateMemberName(event) {
    this.memberName = event.target.value;
    this.loadParticipants();
  }

  @action
  clearFilters() {
    this.selectedRequirementId = '';
    this.selectedMemberId = '';
    this.selectedType = '';
    this.memberName = '';
    this.initializeTimeRange();
    this.loadParticipants();
  }

  @action
  showAddModal() {
    this.editingParticipant = null;
    this.formData = {
      requirementId: this.selectedRequirementId || '', // 默认选中当前筛选的需求
      memberId: '',
      startTime: '',
      endTime: '',
      workload: 0,
      role: '',
      workItem: '',
      type: ''
    };
    this.showModal = true;
  }

  @action
  openBatchModal() {
    this.batchFormData = {
      requirementId: this.selectedRequirementId || '',
      batchStr: ''
    };
    this.showBatchModal = true;
  }


  @action
  hideBatchModal() {
    this.showBatchModal = false;
    this.batchFormData = {
      requirementId: '',
      batchStr: ''
    };
  }

  @action
  updateBatchFormData(field, value) {
    // 处理来自 T::InputSearch 的直接值传递和来自原生输入元素的事件对象传递
    const actualValue = value && value.target ? value.target.value : value;
    this.batchFormData = {
      ...this.batchFormData,
      [field]: actualValue
    };
  }

  @action
  async saveBatchParticipants(event) {
    event.preventDefault();
    
    if (!this.batchFormData.requirementId || !this.batchFormData.batchStr.trim()) {
      this.message.showErrMsg('请选择需求并填写批量文本');
      return;
    }

    this.isLoading = true;

    try {
      await this.api.batchAddRequirementParticipants(this.batchFormData);
      this.message.showMsg('批量新增参与人员成功');
      
      // 保存完成后重新加载数据
      this.args.onRefresh?.();
      this.hideBatchModal();
    } catch (error) {
      console.error('批量新增参与人员失败:', error);
      this.message.showErrMsg('批量新增参与人员失败');
    } finally {
      this.isLoading = false;
    }
  }

  @action
  editParticipant(participant) {
    this.editingParticipant = participant;
    this.formData = {
      requirementId: participant.requirementId?.toString() || '',
      memberId: participant.memberId?.toString() || '',
      startTime: participant.startTime || '',
      endTime: participant.endTime || '',
      workload: participant.workload || 0,
      role: participant.role || '',
      workItem: participant.workItem || '',
      type: participant.type || ''
    };
    this.showModal = true;
  }

  @action
  hideModal() {
    this.showModal = false;
    this.editingParticipant = null;
  }

  @action
  updateFormData(field, value) {
    // 处理来自 T::InputSearch 的直接值传递和来自原生输入元素的事件对象传递
    const actualValue = value && value.target ? value.target.value : value;
    this.formData = {
      ...this.formData,
      [field]: actualValue
    };
  }

  @action
  async saveParticipant(event) {
    event.preventDefault();
    
    if (!this.formData.requirementId || !this.formData.memberId || !this.formData.startTime || !this.formData.endTime || this.formData.workload === '' || this.formData.workload === null || !this.formData.type) {
      // 在实际应用中应该显示错误消息
      return;
    }

    this.isLoading = true;

    try {
      if (this.editingParticipant) {
        // 更新现有参与人员 - 只传递更新数据，不包含ID
        await this.args.onUpdateParticipant?.(this.editingParticipant.id, this.formData);
      } else {
        // 新增参与人员
        await this.args.onAddParticipant?.(this.formData);
      }

      // 保存完成后重新加载数据
      this.args.onRefresh?.();
    } catch (error) {
      console.error('保存参与人员失败:', error);
    } finally {
      this.isLoading = false;
      this.hideModal();
    }
  }

  @action
  async deleteParticipant(participantId) {
    if (confirm('确定要删除这个参与人员吗？')) {
      this.isLoading = true;
      try {
        await this.args.onDeleteParticipant?.(participantId);
        // 删除完成后重新加载数据
        this.args.onRefresh?.();
      } catch (error) {
        console.error('删除参与人员失败:', error);
      } finally {
        this.isLoading = false;
      }
    }
  }
}